//
//  JBWHomeViewModel.swift
//  新浪微博
//
//  Created by 季伯文 on 2017/7/4.
//  Copyright © 2017年 bowen. All rights reserved.
//

import UIKit
import SDWebImage
class JBWHomeViewModel: NSObject {

    //保存首页模型数组
    lazy var dataList:[JBWStatusViewModel] = [JBWStatusViewModel]()
}
extension JBWHomeViewModel {
    func getHomeData(isPullUp: Bool, finish:@escaping (Bool,Int)->()){
        
            //since_id 下拉刷新
            //max_id 上拉加载更多
            var sinceId:Int64 = 0
            var maxId: Int64 = 0
            
            //判断如果是下拉刷新
            if !isPullUp {
                sinceId = dataList.last?.homeModel?.id ?? 0
            } else {
                //上拉加载更多
                maxId = dataList.last?.homeModel?.id ?? 0
                //若指定此参数 返回id小于或等于max_id的微博 默认为0
                if maxId > 0 {
                    maxId -= 1
                }
            }
            
            JBWNetworkTools.share.homeLoadData(since_id: sinceId, max_id: maxId, success: { (response) in
                
            // 判断它是否为nil 而且是否是一个字典
            guard let resDict = response as? [String: Any] else{
                finish(false,0)
                return
            }
            
            // 判断resDict["statuses"] 是否为nil 而且是否是一个[[string:any]]
            guard let resList = resDict["statuses"] as? [[String: Any]] else{
                finish(false,0)
                return
            }
            let tempList = NSArray.yy_modelArray(with: JBWHomeModel.self, json: resList)
            
            // 判断是否为nil 而且是否是一个有模型的数组
            guard let t = tempList as? [JBWHomeModel] else{
                finish(false,0)
                return
            }
            
            //创建一个临时数组
            var tempStatusList:[JBWStatusViewModel] = [JBWStatusViewModel]()
            
            //创建调度组
            let group = DispatchGroup()
            
            //遍历保存模型的数组
            for homeModel in t {
                
                //下载单张图片
                //如果是原创微博 且为一张
                if homeModel.pic_urls?.count == 1 {
                    group.enter()
                    SDWebImageManager.shared().loadImage(with: URL(string: homeModel.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                        print("原创微博图片下载完成")
                        group.leave()
                    })
                }
                //如果是转发微博 且为一张
                if homeModel.retweeted_status?.pic_urls?.count == 1 {
                    group.enter()
                    SDWebImageManager.shared().loadImage(with: URL(string: homeModel.retweeted_status?.pic_urls?.first?.thumbnail_pic ?? ""), options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                        print("转发微博图片下载完成")
                        group.leave()
                    })
                }

                //创建一个viewModel
                let statusViewModel = JBWStatusViewModel()
                //赋值
                statusViewModel.homeModel = homeModel
                //保存
                tempStatusList.append(statusViewModel)
            }
      
                //下拉刷新
                if !isPullUp {
                    // 赋值
                    self.dataList = tempStatusList + self.dataList
                } else {
                    //上拉加载更多
                    self.dataList = self.dataList + tempStatusList
                }
            //使用调度组来监听单张图片是否下载完成
            group.notify(queue: DispatchQueue.main, execute: { 
                print("单张图片下载完成")
                //执行成功
                finish(true,tempStatusList.count)
            })
        }) { (error) in
            print("请求失败",error)
            finish(false,0)
        }
    }
}

